| Author | |
|---|---|
| Name | Claire Descombes |
| Affiliation | Universitätsklinik fßr Neurochirurgie, Inselspital Bern |
| Degree | MSc Statistics and Data Science, University of Bern |
| Contact | claire.descombes@insel.ch |
The reference material for this course, as well as some useful literature to deepen your knowledge of R, can be found at the bottom of the page.
When you get a file from somewhere on your computer (e.g. a dataset), you can either
The advantage of putting the files in the folder that contains your script and is set as the working directory is that you can easily move the folder around on your computer without getting any problems with your script: just set the working directory to your source file every time you open it, and youâll be fine.
# Example
setwd("~/path/to/your/folder/")
data <- read.csv("testdata.csv")
The advantage of always giving the full path to a file is that you can get data in different folders on your computer, avoiding things like copying the source data in every folder where you have a corresponding script.
# Example
data <- read.csv("~/path/to/your/folder/testdata.csv")
Working directory
To tell R which folder you are working in (e.g., where your data is stored), you have several options:
setwd("path/to/your/folder") in your script.đĄ Tip: To avoid file path errors and keep your project organized,
itâs best to store your script and data files in the same folder â or at
least place your data files in a subfolder like data_sets
within your project directory. Then, set that folder as your working
directory in R. This ensures that your code can reliably find and save
your files.
getwd() # Displays the current working directory
setwd("~/path/to/your/folder") # Sets the working directory
We will first look at how to import a CSV file into R as a data frame.
CSV stands for Comma-Separated Values. In a .csv file,
the values are stored as plain text, separated by commas. This is a
simple and widely used format for storing tabular data.
After setting your working directory or determining the path to your
CSV file, you can use the read.csv() function to import the
data. This will create a data frame, which is one of the most commonly
used structures in R for handling datasets.
# Import a CSV file into a data frame
dataset <- read.csv("~/path/to/your/folder/data.csv")
đĄ I recommend using data frames â they are generally easier to work with than matrices, especially for beginners.
Another widely used data format is the Excel file
(.xlsx). For these, you can use the readxl
package to import the data:
# Load the readxl package (after installing it)
library(readxl)
# Read the first sheet of an Excel file
dataset <- read_excel("~/path/to/your/folder/data.xlsx")
â ď¸ Note: If your file is actually a CSV but mistakenly has a .xlsx extension, you should rename it to .csv and use read.csv() instead. Mixing up formats can lead to import errors.
Let us now look at real data frames to learn how to call or modify
their elements. To do this, we will use multiple health data sets from
the National Health and Nutrition Examination (NHANES) Survey
from 2011-2012. The survey assessed overall health and nutrition of
adults and children in the United States and was conducted by the
National Center for Health Statistics (NCHS). The data sets can be found
in the data_sets
folder.
| Dataset | NHANES Code | Description | CSV File |
|---|---|---|---|
| Demographics | DEMO_G | Age, sex, race/ethnicity, income, education | DEMO_G.csv |
| Blood Pressure | BPX_G | Systolic/diastolic blood pressure, number of readings | BPX_G.csv |
| Body Measures | BMX_G | Height, weight, BMI, waist circumference | BMX_G.csv |
| Smoking Questionnaire | SMQ_G | Smoking habits, exposure to secondhand smoke | SMQ_G.csv |
# Load the necessary CSV files into data frames
demo <- read.csv("/home/claire/Documents/GitHub/rforphysicians/data_sets/DEMO_G.csv") # Demographics (cycle G = 2011â2012)
bpx <- read.csv("/home/claire/Documents/GitHub/rforphysicians/data_sets/BPX_G.csv") # Blood pressure
bmx <- read.csv("/home/claire/Documents/GitHub/rforphysicians/data_sets/BMX_G.csv") # Body measures
smq <- read.csv("/home/claire/Documents/GitHub/rforphysicians/data_sets/SMQ_G.csv") # Smoking questionnaire
đĄ The codebook for each data set can be accessed either on the NCHS website
or directly in R using the function
nhanesCodebook(nh_table, colname) from the package
nhanesA (which I used to download the data). Youâll also
find a summary of key variables from each data set at the end of this
chapter.
âď¸ Exercise on the NHANES data sets n°1: import the
demo, bpx, bmx and
smq data sets from the data_sets
folder into R.
tidyverseBase R, without any additional packages, already provides many functions that are very handy for data handling. However, some contributed packages make data preparation much easier and more readable.
Iâll introduce two such packages here, before diving into concrete
data handling examples. Both are part of a larger and very powerful
collection of packages for data science called the
tidyverse, which I use for nearly all my analyses.
One of the most downloaded contributed extension packages of all
times is magrittr. It provides a very useful operator, the
forward pipe operator %>%, which passes the object on
its left as the first argument to the function on its right. This is
much easier to understand with an example.
# The easiest way to get magrittr is to install the whole tidyverse
install.packages("tidyverse")
# Once installed, a package has to be loaded to be used
library(tidyverse)
library(tidyverse)
# Let's do the same operation twice: once using the pipe, once without
# No pipe:
str(c(1,2,3,4))
## num [1:4] 1 2 3 4
# With pipe:
c(1,2,3,4) %>%
str()
## num [1:4] 1 2 3 4
# Not too exciting yet, but consider a more complex case:
summary(log(sqrt(na.omit(c(1, 4, NA, 16, 25)))))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000 0.5199 1.0397 0.9222 1.4421 1.6094
# With the pipe, we can rewrite this more readably:
c(1, 4, NA, 16, 25) %>%
na.omit() %>%
sqrt() %>%
log() %>%
summary()
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0000 0.5199 1.0397 0.9222 1.4421 1.6094
The pipe helps turn nested function calls into a sequence of simpler,
linear steps. This makes code easier to read, write, and debug. The pipe
becomes especially powerful when used with functions from the
dplyr package for data manipulation.
dplyrAnother helpful R package is dplyr. It is a grammar of
data manipulation, providing a consistent set of verbs that helps solve
the most common data manipulation challenges.
Letâs illustrate this with a simple example. Our goal: Group the cars dataset (contained in base R) by speed groups (e.g. low/medium/high), and for each group, compute (1) the average stopping distance and (2) the number of observations.
# Base R (no dplyr, no pipe)
cars$speed_group <- cut(cars$speed, breaks = c(0, 10, 20, 30),
labels = c("Low", "Medium", "High"))
avg_dist <- aggregate(dist ~ speed_group, data = cars, mean)
n_obs <- aggregate(dist ~ speed_group, data = cars, length)
names(n_obs)[2] <- "n"
summary_df <- merge(avg_dist, n_obs, by = "speed_group")
summary_df
# With dplyr, no pipe:
cars <- mutate(cars, speed_group = cut(speed, breaks = c(0, 10, 20, 30), labels = c("Low", "Medium", "High")))
summary_df <- summarise(group_by(cars, speed_group),
avg_dist = mean(dist),
n = n())
summary_df
# With dplyr and the pipe
cars %>%
mutate(speed_group = cut(speed, breaks = c(0, 10, 20, 30),
labels = c("Low", "Medium","High"))) %>%
group_by(speed_group) %>%
summarise(
avg_dist = mean(dist),
n = n()
)
đĄ cut(x, ...) divides the range of x into
intervals (the breaks) and codes the values in x according
to which interval they fall. labels are the levels of the
resulting category. If labels = FALSE, simple integer codes
are returned instead of a factor.
As you can see, using dplyr and the pipe can make your
life much easier.
In the following chapter, weâll use both base R and
tidyverse functions without always noting which package
they belong to. If youâre ever unsure, you can check the top-left corner
of the functionâs help page.
Being able to access elements in a data frame is essential when working with data. Here are some common methods to select specific elements, rows, or columns.
# Look at the first respectively last few rows
head(demo)
tail(demo)
# Select columns by name
demo[, c("RIDAGEYR", "RIAGENDR")] # Selecting age in years and gender
vars <- c("RIDAGEYR", "RIAGENDR")
demo[, vars] # Alternative using variable `vars`
# Select elements by position
demo[1, 1] # Access the first element of the first column (the respondent sequence number of the 1st participant)
## [1] 62161
ind_mat <- cbind(c(1, 3, 5), c(2, 4, 6))
demo[ind_mat] # Access rows and columns using multiple indices
## [1] "NHANES 2011-2012 public release" "Male"
## [3] NA
# Select rows based on a condition
head(demo[, "RIDAGEYR"] > 50) # Logical condition for age greater than 50
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
head(!(demo[, "DMDHHSIZ"] > 3)) # Logical negation for total number of people in the household not greater than 3
## [1] FALSE FALSE FALSE FALSE FALSE FALSE
demo[demo[, "RIDAGEYR"] > 50, ] # Rows where age > 50
demo[demo[, "DMDHHSIZ"] < 3, ] # Rows where total number of people in the household greater than 3
demo[demo[, "DMDHHSIZ"] >= 3, ] # Rows where total number of people in the household greater or equal 3